<template>
  <div class="flex flex-col bg-white flex-auto">
    <TabBar v-model:active="active" :tabs="cp_tabs" @click-tab="onClickTab" />

    <div class="flex-auto overflow-y-auto" v-ai-tip>
      <MindMapSummary v-if="currentTab.type === SummaryTabType.SummaryMindType" />
      <QAReview v-else-if="currentTab.type === SummaryTabType.QAReviewType" />
      <SummarySegmented
        v-else-if="currentTab.type === SummaryTabType.SegmentedSummaryType"
      />
      <SummarySpeech v-else-if="currentTab.type === SummaryTabType.SummarySpeechType" />

      <SummaryCommon
        v-else-if="currentTab.type === SummaryTabType.MeetSummaryType"
        :report="currentTab.report"
        :show-copy-btn="true"
      />

      <template v-else-if="currentTab.type === SummaryTabType.BusinessOpportunityType">
        <div
          v-if="currentMethodologyLoading"
          class="flex flex-row items-center w-full h-[100px] justify-center gap-2"
        >
          <van-loading size="24" />
          <span class="loading-text">AI正在全力生成数据...</span>
        </div>
        <SummaryCommon
          v-else
          :report="currentMethodologyContent"
          :defaultSelectedModelKey="currentMethodology?.key"
          :show-copy-btn="true"
        />
      </template>
      <SummaryCommon
        v-else
        :report="currentTab.report"
        :defaultSelectedModelKey="currentMethodology?.key"
        :show-copy-btn="true"
      />
    </div>
  </div>

  <van-action-sheet
    v-model:show="showChooseModel"
    teleport="#minutesPage"
    title="选择模型"
  >
    <ChooseAnalyzeLat
      @confirm="handleModelConfirm"
      :defaultSelectedModelKey="currentMethodology?.key"
    />
  </van-action-sheet>
</template>

<script setup lang="ts">
import { computed, ComputedRef, ref, reactive, onMounted } from "vue";
import TabBar from "@/components/CustomTabBar.vue";
import { EventBusEnum, SalesSummaryReport, SummaryTab, SummaryTabType } from "@/types";
import { MethodologyType, MethodologyData } from "./modelMap";
import { useMinutesStore } from "@/store";
import { getModelWithKey } from "./modelMap";

import ChooseAnalyzeLat from "./chooseAnalyzeLat.vue";
import MindMapSummary from "./mindMap/MindMapSummary.vue";
import QAReview from "@/views/minutes/components/summary/Q&A/QAReview.vue";
import SummarySegmented from "@/views/minutes/components/summary/summarySegmented/index.vue";
import SummarySpeech from "./SummarySpeech/index.vue";
import SummaryCommon from "./summaryCommon/indev.vue";
import EventBus from "@/EventBus.js";

const store = useMinutesStore();
const active = ref(0);
const salesSummaryReports: ComputedRef<SalesSummaryReport[]> = computed(
  () => store.report.salesSummaryReports || []
);

// 选择方法论
const showChooseModel = ref(false);

// 用于缓存每种方法论类型的 loading 和 content
const modelContentMap = reactive<
  Record<string, { loading: boolean; data?: MethodologyData }>
>({});

function onClickTab(v: any) {
  const tab: SummaryTab = v.tab;
  const index: number = v.index;
  if (index !== active.value) return;
  if (!tab.iconName) return;
  showChooseModel.value = true;
}

onMounted(() => {
  if (defaultSalesMethodology.value) {
    handleModelConfirm(defaultSalesMethodology.value);
  }
});

const defaultSalesMethodology = computed(() => {
  return getModelWithKey(
    salesSummaryReports.value.find((v) => v.systemId === 8)?.defaultSalesMethodology ||
      "NORMAL"
  );
});

const currentMethodologyName = ref(defaultSalesMethodology.value?.name || "商机识别");

const currentMethodology = ref<MethodologyType | null>(defaultSalesMethodology.value);
async function handleModelConfirm(model: MethodologyType) {
  currentMethodologyName.value = model.name;
  currentMethodology.value = model;
  showChooseModel.value = false;
  const key = model.value;
  // 如果已存在内容或正在 loading，直接返回
  if (modelContentMap[key]?.data || modelContentMap[key]?.loading) {
    return;
  }
  // 初始化 loading 状态
  if (!modelContentMap[key]) {
    modelContentMap[key] = { loading: false, data: undefined };
  }
  modelContentMap[key].loading = true;
  try {
    const data: MethodologyData = await store.getAnalyzeLatAction(model.value);
    modelContentMap[key].data = data;
  } finally {
    modelContentMap[key].loading = false;
  }
}
const currentMethodologyLoading = computed(() => {
  return modelContentMap[currentMethodology.value?.value || 0]?.loading;
});

const currentMethodologyContent = computed(() => {
  return (
    modelContentMap[currentMethodology.value?.value || 0]?.data?.content ||
    currentTab.value.report
  );
});

const currentTab = computed(() => cp_tabs.value[active.value]);

const cp_tabs = computed(() => {
  let array: SummaryTab[] = [];

  for (let index = 0; index < salesSummaryReports.value.length; index++) {
    const item: SalesSummaryReport = salesSummaryReports.value[index];
    const { report, systemId, name, systemPreset, defaultSalesMethodology } = item;

    let tabItem: SummaryTab = {
      title: name,
      systemPreset: systemPreset,
      report: report,
      type: mapSystemIdToType(systemId),
    };
    if (tabItem.type === SummaryTabType.BusinessOpportunityType) {
      tabItem.title = currentMethodologyName.value;
      tabItem.iconName = "arrow-down";
      tabItem.defaultSelectedModelKey = defaultSalesMethodology;
    }
    array.push(tabItem);
  }
  return array;
});

function mapSystemIdToType(systemId: number): SummaryTabType {
  if (systemId === 1) return SummaryTabType.SegmentedSummaryType;
  if (systemId === 2) return SummaryTabType.QAReviewType;
  if (systemId === 3) return SummaryTabType.SummarySpeechType;
  if (systemId === 4) return SummaryTabType.MeetSummaryType;
  if (systemId === 5) return SummaryTabType.SalesMaterSummaryType;
  if (systemId === 6) return SummaryTabType.ResearchReportType;
  if (systemId === 7) return SummaryTabType.SummaryMindType;
  if (systemId === 8) return SummaryTabType.BusinessOpportunityType;

  return SummaryTabType.UnknownType;
}
</script>

<style scoped></style>
